package com.archerdu.demo;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectDemo {

    /**
     * 获取实体类信息
     * 
     * @param obj
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static String getProperties(Object obj) {
        StringBuffer sb = new StringBuffer("{");

        Class c = obj.getClass();

        Method[] methods = c.getMethods();
        for (int i = 0; i < methods.length; i++) {
            String temp = methods[i].getName();
            if (temp.startsWith("get") && methods[i].getParameterTypes().length == 0 && !temp.startsWith("getClass")) {
                try {
                    sb.append(temp.substring(3).toLowerCase() + ":" + methods[i].invoke(obj) + ",");
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        if (sb.length() > 1) {
            sb.deleteCharAt(sb.length() - 1);
        }
        sb.append("}");
        return sb.toString();
    }
}
